package com.regenlife.configuration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import java.io.FileFilter;

/**
 * This class load configuration items from properties files located in the specified location by environment variable
 * CATALINA_HOME. It works well for windows and linux, for windows, you can specify CATALINA_HOME as "d:\tomcat\" at OS level, 
 * as well as /var/tomcat/ on linux.  
 * 
 * All properties files and only properties files are loaded into this class. This is to prevent the auto-generated .bak files 
 * from being loaded. 
 * 
 * @author ylei
 */
public class ConfigurationUtils {
    private static String nameOS = "os.name";
    private String configBasePath;
    private String configFilePath;
    private Properties prop;

    public ConfigurationUtils() {
        configBasePath = System.getenv("CATALINA_HOME");
        if (isWindowsOs()) {
            configFilePath = configBasePath + "\\app\\config\\";
        } else {
            configFilePath = configBasePath + "/app/config/";
        }
        prop = new Properties();
        loadConfigurations();
    }
    
    public String getValue(String key) {
        return (String) prop.get(key);
    }

    private void loadConfigurations() {
        File f = new File(configFilePath);
        if (!f.exists()) {
            return;
        }
        File[] filesOrDirs = f.listFiles(new PropertiesFileFilter());
        String[] result = new String[filesOrDirs.length];
        try {
            for (int i = 0; i < filesOrDirs.length; i++) {
                if (filesOrDirs[i].isDirectory()) {
                    ; // skip directory
                } else {
                    result[i] = filesOrDirs[i].getName();
                    String fullFileName = configFilePath + result[i];
                    InputStream is = new FileInputStream(fullFileName);
                    prop.load(is);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isWindowsOs() {
        String osName = System.getProperty(nameOS);
        if (osName.indexOf("Windows") != -1) {
            return true;
        } else {
            return false;
        }
    }

    private final class PropertiesFileFilter implements FileFilter {
        private final String[] okFileExtensions = new String[] { "properties" };

        public boolean accept(File file) {
            for (String extension : okFileExtensions) {
                if (file.getName().toLowerCase().endsWith(extension)) {
                    return true;
                }
            }
            return false;
        }
    }

}
